﻿import ShowFormMenuLayout from '@/components/FormItemComponents/FormLayoutComponents.vue'
// 展示审核步骤的页面
import stepsShow from '@/views/workflow/workflowShow/StepsInfo.vue'
// 展示流程图的页面
import workflowShow from '@/views/workflow/workflowShow/WorkflowShow.vue'
// 引入公共的基础部分
import ExtendWorkflow from '@/components/extendComponents/ExtendWorkflow.vue'
// 引入选人的弹窗
import ChooseUsers from '@/components/ChooseUser.vue'
export default {
  props: ['dynamicUid', 'dynamicMenuDialogVisible', 'currentRow', 'dialogType', 'primaryKey', 'pPageRow'],
  extends: ExtendWorkflow,
  name: 'DynamicWorkflowMenuDialog',
  data () {
    return {
      // 弹窗相关的信息
      dialogTitle: '',
      dialogFormVisible: false,
      clickRow: '',
      // 嵌套的弹窗
      dialogEx: {
        relatedPageUid: '',
        retatedPageVisible: false,
        clickRow: '',
        dialogType: ''
      }
    }
  },
  methods: {
    // 初始化页面
    init () {
      this.loading = true
      this.models = {}
      this.rules = {}
      this.clickRow = ''
      this.allSingleElement = []
      this.pageFormInfo = ''
      this.workflowBtnStatus = {
        Delete: [],
        Save_add: [],
        Save_edit: [],
        Submit: [],
        Pass: [],
        Reject: [],
        SelectReject: [],
        Stop: [],
        Apply: [],
        SubmitPending: [],
        ActivePending: []
      }
      this.currentShow = 'basicInfo'
      this.workFlowParams = {
        primaryKey: this.primaryKey || '',
        status: '',
      }
      this.pagePrimaryObj = {
        inputArray: [],
        outputArray: []
      }
      this.currentEventsArray = []
      if (this.currentRow && !this.$isEmptyObject(this.currentRow)) {
        this.clickRow = JSON.parse(JSON.stringify(this.currentRow))
      }
      // 对于特殊的需要选人的节点
      this.NextUserList = null
      this.currentClickType = ''
      this.showUserDialog = false
      this.getFunInfo(this.dynamicUid)
    },
    // 获取功能的设定信息---定义好表头及功能的基本信息
    getFunInfo (uid) {
      this.$basicWFGet('/d_form/' + uid).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.loading = false
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
        }
        if (dataInfo.code === 'success') {
          if (this.dialogType.indexOf('edit') !== -1) {
            this.dialogTitle = '编辑信息'
          } else if (this.dialogType.indexOf('add') !== -1) {
            this.dialogTitle = '新增信息'
          } else if (this.dialogType.indexOf('handle') !== -1) {
            this.dialogTitle = '办理信息'
          }
          if (dataInfo.data.is_warnning) {
            this.$message({
              type: 'warning',
              message: dataInfo.data.warnning_msg,
              showClose: true,
              duration: 0
            })
          } else if (dataInfo.data.is_error) {
            this.$message({
              type: 'error',
              message: dataInfo.data.error_msg
            })
            this.loading = false
          }
          if (dataInfo.data.settings && !dataInfo.data.is_error) {
            this.pageFormInfo = JSON.parse(dataInfo.data.settings)
            // console.log(this.pageFormInfo)
            if (this.pageFormInfo.pageConfig.name) {
              this.dialogTitle = this.pageFormInfo.pageConfig.name
              if (this.dialogType === 'showDetail') {
                this.dialogTitle += '（详情）'
              }
            }
            // 获取流程表单的按钮显示状态和按钮事件
            this.getWorkflowBtnStatus(this.pageFormInfo.pageConfig)
            // 当页面有初始化事件时
            if (this.pageFormInfo.pageConfig.events.length) {
              this.currentEventsArray = []
              this.pageFormInfo.pageConfig.events.forEach(item => {
                if (item.eventsType === 'initPage') {
                  this.currentEventsArray.push(item)
                }
              })
              // 如果有页面初始化事件，就执行
              if (this.currentEventsArray.length) {
                this.currentEventsArray.sort(this.orderByObjAttr('actionIndex'))
                this.getEventsInfoByEventNo(this.models, this.currentEventsArray[0].eventsNo, 'isInit', 1, null)
              }
            }
            // 获取表单的基本信息
            this.getFormInfo(this.pageFormInfo.list)
            this.changeModels = !this.changeModels
            this.loading = false
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    afterEval (dataCode, dataResult, isInit, eventItemNo, workflowEventIndex, workflowEventItem, dataMsg) {
      if (dataCode === 'failed') {
        this.loading = false
        this.$message({
          message: dataMsg,
          type: 'warning'
        })
      } else if (dataCode === 'success') {
        // 触发事件后，需要判断获取的值是否需要用到下一个事件中
        this.changeOutputParames(dataResult, eventItemNo)
        if (isInit) {
          this.$nextTick(() => {
            if (dataResult && !this.$isEmptyObject(this.models)) {
              let dataObj = dataResult
              if (this.$isArray(dataResult)) {
                dataObj = dataResult[0]
              }
              for (let rowKey in dataObj) {
                for (let modelKey in this.models) {
                  if (modelKey === rowKey) {
                    this.$set(this.models, modelKey, dataObj[rowKey])
                  }
                }
              }
            }
            this.changeModels = !this.changeModels
          })
          if (this.currentEventsArray.length === workflowEventIndex) {
            // 如果是最后一个事件
            this.loading = false
            this.currentEventsArray = []
          } else {
            this.getEventsInfoByEventNo(this.models, this.currentEventsArray[workflowEventIndex].eventsNo, 'isInit', workflowEventIndex + 1, null)
          }
        } else {
          // 当为流程事件时---要判断是否是该流程下的最后一个事件
          if (workflowEventItem) {
            // 是最后一个事件时
            if (this.workflowBtnStatus[workflowEventItem.eventType].length === workflowEventIndex) {
              this.loading = false
              this.currentEventsArray = []
              let msg = (workflowEventItem.eventType === 'Save_add' || workflowEventItem.eventType === 'Save_edit') ? '保存成功' : ( workflowEventItem.eventType === 'Delete' ? '删除成功' : '操作成功')
              this.$confirm(msg, '提示', {
                showClose: false,
                showCancelButton: false,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                confirmButtonText: '确定'
              }).then(() => {
                // 保存时不需要刷新窗口
                // if (workflowEventItem.eventType !== 'Save_add' && workflowEventItem.eventType !== 'Save_edit') {
                //   this.$refs['formMenuLayout'].resetValidate()
                //   this.$emit('closeDynamicMenuDialogSuccess')
                // }
                this.$refs['formMenuLayout'].resetValidate()
                this.$emit('closeDynamicMenuDialogSuccess')
              }).catch(() => {})
            } else {
              // 还有其它的事件需要执行
              // 需要判断下一个事件是不是执行流程事件
              if (this.workflowBtnStatus[workflowEventItem.eventType][workflowEventIndex].sortNum === 0) {
                this.executeWorkflow(workflowEventIndex + 1, workflowEventItem)
              } else {
                this.getEventsInfoByEventNo(this.models, this.workflowBtnStatus[workflowEventItem.eventType][workflowEventIndex].eventsNo, null, workflowEventIndex + 1, workflowEventItem)
              }
            }
          } else {
            if (this.currentEventsArray.length === workflowEventIndex) {
              // 如果是最后一个事件
              this.currentEventsArray = []
              this.$message({
                message: dataMsg,
                type: 'success'
              })
              this.loading = false
              this.$refs['formMenuLayout'].resetValidate()
              this.$emit('closeDynamicMenuDialogSuccess')
            } else {
              this.getEventsInfoByEventNo(this.models, this.currentEventsArray[workflowEventIndex].eventsNo, null, workflowEventIndex + 1, null)
            }
          }
        }
      } else if (dataCode === 'failedToClose') {
        this.loading = false
        this.currentEventsArray = []
        this.$emit('closeDynamicMenuDialog')
        this.$message({
          message: dataMsg,
          type: 'success'
        })
      }
    },
    // 处理行事件时
    handelRowEvents (fromChildItem) {
      if (fromChildItem && fromChildItem.eventsArray && fromChildItem.eventsArray.length) {
        this.loading = true
        this.clickRow = fromChildItem.clickRow
        this.currentEventsArray = JSON.parse(JSON.stringify(fromChildItem.eventsArray))
        this.getEventsInfoByEventNo(this.models, this.currentEventsArray[0].eventsNo, null, 1, null)
      }
    },
    // 打开关联的页面
    openDialog (fromChildItem) {
      if (fromChildItem && fromChildItem.eventsArray && fromChildItem.eventsArray.length) {
        if (fromChildItem.eventsArray[0].dialogUid) {
          this.dialogEx.retatedPageVisible = true
          this.dialogEx.relatedPageUid = fromChildItem.eventsArray[0].dialogUid
          this.dialogEx.clickRow = fromChildItem.clickRow
          this.dialogEx.dialogType = fromChildItem.eventsArray[0].eventsType
        } else {
          this.$message({
            message: '还没有指定需要打开的页面，请前往资源管理进行配置',
            type: 'warning'
          })
        }
      }
    },
    // 关闭关联的页面时(需要刷新页面)
    closeDynamicMenuDialogSuccess () {
      this.dialogEx.retatedPageVisible = false
      this.init()
    },
    // 取消表单时
    resetFormData () {
      this.$refs['formMenuLayout'].resetValidate()
      this.$emit('closeDynamicMenuDialog')
    },
    // 关闭弹窗
    closeDialog () {
      this.$refs['formMenuLayout'].resetValidate()
      // this.$emit('closeDynamicMenuDialog')
      this.$emit('closeDynamicMenuDialogSuccess')
    },
    // 刷新当前页面
    reloadCurrentPage () {
      this.init()
    }
  },
  watch: {
    // 监听弹窗打开的方法
    dynamicMenuDialogVisible: {
      handler: function (val, oldVal) {
        this.dialogFormVisible = val
        if (val) {
          this.init()
        } else { // 弹窗关闭时,销毁model
          this.models = {}
          this.changeModels = !this.changeModels
        }
      }
    }
  },
  components: {
    ShowFormMenuLayout, workflowShow, stepsShow, ChooseUsers
  }
}
